package com.warrior.TaskScheduled;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.warrior.entity.WxCache;
import com.warrior.service.WxCacheService;
import com.warrior.util.WxChatAuthTools;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * spring 定时器,定期获取token
 * Created by Shawn on 2017/4/6.
 */
@Component
public class TaskSaveToken {

    @Autowired
    private WxCacheService wxCacheService;

    private static final Logger logger = LogManager.getLogger(TaskSaveToken.class.getName());

    /**
     * 每隔1h获取一次token,并存放在数据库中
     */
    public void getTokenAndTicket() {
        if (logger.isDebugEnabled()) {
            logger.debug("getTokenAndTicket() - start"); //$NON-NLS-1$
        }
        logger.debug("定时任务开始");
        WxChatAuthTools wxChatAuthTools = new WxChatAuthTools();
        String wxAccessToken = wxChatAuthTools.getWxAccessToken();
        try {
            String jsapiTicket = wxChatAuthTools.getJsapiTicket(wxAccessToken);
            //删除之前的cache
            this.wxCacheService.deleteCache();
            //将token和 jsapiTicket 存入数据库
            ObjectMapper mapper = new ObjectMapper();
            WxCache wxCache = new WxCache();
            Map returnData = mapper.readValue(wxAccessToken, Map.class);
            String access_token = (String) returnData.get("access_token");
            wxCache.setAccessToken(access_token);
            Map jsapiTicketData = mapper.readValue(jsapiTicket, Map.class);
            String ticket = (String) jsapiTicketData.get("ticket");
            wxCache.setJsapiTicket(ticket);
            this.wxCacheService.saveWxCache(wxCache);
        } catch (IOException e) {
            logger.error("getTokenAndTicket()", e); //$NON-NLS-1$
            e.printStackTrace();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("getTokenAndTicket() - end"); //$NON-NLS-1$
        }
    }


}
